<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-submit>
            <el-button :disabled="!canSubmit" @click="submit(tableInfo.selections)">提交 </el-button>
          </template>
          <template v-slot:filter-remove>
            <el-button :disabled="!canRemove" @click="remove(tableInfo.selections)">删除 </el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('provinceRejected:detail')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo || "-" }}</span
          >
          <span v-else>{{ scope.row.orderNo || "-" }}</span>
        </template>
      </TableContainer>
    </div>
    <!-- 新增或修改 -->
    <modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :orderId="modifyInfo.orderId"
      @returnModify="returnModify"
    />
    <detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :orderId="detailInfo.orderId"
      @returnBack="getList"
    />

    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
  </div>
</template>
<script setup name="provinceRejected">
import { provinceReturnOrder, deleteProvinceReturnOrder, submitProvinceReturnOrder } from "@/api/province";
import { getCustomizeSetting, updateUserCustomize } from "@/api/customize";
import modify from "./modify";
import detail from "./detail";

const detailList = defineAsyncComponent(() => import("./detailList"));

const { proxy } = getCurrentInstance();

const listTypeInfo = ref({
  supplierList: [],
  typeList: [],
});
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: "",
    customizeUserVO: {},
    queryMap: {},
  },
  searchList: [],
  btnList: [
    {
      type: "button",
      label: "新增",
      event: create,
      show: proxy.$permission("provinceRejected:add"),
    },

    {
      type: "slot",
      value: "submit",
      show: proxy.$permission("provinceRejected:submit"),
    },
    {
      type: "slot",
      value: "remove",
      show: proxy.$permission("provinceRejected:delete"),
    },
  ],
  searchBtn: [
    { type: "button", label: "搜索", event: _search },
    { type: "button", label: "高级查询", event: _advancedSearchShow },
    { type: "button", label: "重置", event: _clearSearch },
  ],
});
const detailListInfo = ref({
  visible: false,
});
const preferenceInfo = ref({
  visible: false,
});
const advancedSearchInfo = ref({
  visible: false,
  data: {},
});
const clearType = ref(true);
const slipSelectRequest = ref(true);
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: "right",
    label: "操作",
    width: "100",
    btList: [
      {
        label: "修改",
        event: update,
        show: proxy.$permission("provinceRejected:update"),
        ifRender: function (row) {
          return row.status === 1;
        },
      },
      {
        label: "提交",
        event: submit,
        show: proxy.$permission("provinceRejected:submit"),
        ifRender: function (row) {
          return row.status === 1;
        },
      },

      {
        label: "删除",
        event: remove,
        show: proxy.$permission("provinceRejected:delete"),
        ifRender: function (row) {
          return row.status === 1;
        },
      },
    ],
  },
});
//明细相关
const detailInfo = ref({
  visible: false,
  orderId: "",
});

//新增或更新相关
const modifyInfo = ref({
  visible: false,
  title: "",
  orderId: "",
});

const tableKey = ref(
  "provinceReturnOrderList-com.slip.spd.entity.vo.provincePlatform.ProvinceReturnOrderVO"
);
const canRemove = computed(() => {
  return (
    tableInfo.value.selections.filter((item) => item.status === 1).length !== 0
  );
});
const canSubmit = computed(() => {
  return (
    tableInfo.value.selections.filter((item) => item.status === 1).length !== 0
  );
});

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage;
});

let stopWatch = function() {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus;
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === "purchOrder" && el.url === val.url) {
                detailInfo.value.visible = false;
                modifyInfo.value.visible = false;
                detailInfo.value.visible = false;
                if (val.urlType === 1) {
                  getList();
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.value.visible = true;
                    detailInfo.value.orderId = val.businessId;
                    sessionStorage.setItem("storeRowId", val.businessId);
                  });
                }
                proxy.$store.dispatch("settings/toPage", "");
              }
            });
          }
        });
      }
    },
    {
      deep: true,
      immediate: true,
    }
  );
})
onDeactivated(() => {
  stopWatch()
})

setData();
function setData() {
  let obj = {
    statusValue: {
      label: "状态",
      value: "statusValue",
      asValue: "status",
      componentType: "select-model",
      code: "province_platform_order_status",
      show: false,
      hidden: true,
    },
    networkProductTypeValue: {
      label: "挂网产品类型",
      value: "networkProductTypeValue",
      asValue: "networkProductType",
      componentType: "select-model",
      code: "network_product_type",
      show: false,
      hidden: true,
    },
    returnTypeValue: {
      label: "退货方式",
      value: "returnTypeValue",
      asValue: "returnType",
      componentType: "select-model",
      code: "return_type",
      show: false,
      hidden: true,
    },
  };
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  });
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  });
  getCustomize();
}
function _search() {
  search();
}
function _advancedSearchShow() {
  advancedSearchShow();
}
function _clearSearch() {
  clearSearch();
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value);
    }
  });
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true;
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random();
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {};
  filterInfo.value.query.queryDtoList = [];
  tableInfo.value.initCurpage = Math.random();
  tableInfo.value.refresh = Math.random();
}
function clearSearch() {
  clearType.value = !clearType.value;
  advancedSearchInfo.value.data = {};
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  );
  search();
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case "tableCheck":
      tableInfo.value.selections = [...data];
      break;
  }
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem("storeRowId");
  if (rowId && row.id === Number(rowId)) {
    return "check-row";
  }

  return "";
}

function returnModify() {
  if (modifyInfo.value.orderId) {
    getList();
  } else {
    search();
  }
}

// 创建
function create() {
  modifyInfo.value.visible = true;
  modifyInfo.value.title = "新增退货单";
  modifyInfo.value.orderId = "";
}
// 编辑
function update(data) {
  sessionStorage.setItem("storeRowId", data.id);
  modifyInfo.value.visible = true;
  modifyInfo.value.title = "修改退货单";
  // 显示信息
  modifyInfo.value.orderId = data.id;
}
//删除
function remove(row) {
  const ids = [];
  if(Array.isArray(row)) {
    row.map(i => {
      ids.push(i.id)
    })
  } else {
    ids.push(row.id);
  }
  proxy.$handleAPI("delete", deleteProvinceReturnOrder, ids).then((resp) => {
    if (resp && resp.success) {
      getList();
    }
  });
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem("storeRowId", row.id);
  detailInfo.value.orderId = row.id;
  detailInfo.value.visible = true;
}

async function advancedSearchCallback(obj) {
  console.log(123);
  let _filterInfo = filterInfo.value;
  _filterInfo.query.queryMap = {};
  let arr = [
    // {
    //   fieldName: "deptId",
    //   queryType: "IN",
    //   queryCategory: "AND",
    //   value: "deptAuth",
    // },
  ];
  _filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr];
  advancedSearchInfo.value.data = obj.data;
  await getList();
  clearType.value = !clearType.value;
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap);
}
function submit(row = undefined) {
  const ids = [];
  if(Array.isArray(row)) {
    row.map(i => {
      ids.push(i.id)
    })
  } else {
    ids.push(row.id);
  }
  submitProvinceReturnOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList();
    }
  });
}

function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value;
  let _filterInfo = filterInfo.value;
  let param = {
    tableKey: tableKey.value,
  };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      filterInfo.value.query.customizeUserVO = data;
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      );
      console.log(_tableInfo.fieldList);
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      );
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      };
      _filterInfo.searchList = searchInfo.searchList;
      _filterInfo.searchList.forEach((item) => {
        item.event = search;
      });
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      );
      slipSelectRequest.value = _slipSelectRequest;
      _tableInfo.api = provinceReturnOrder;
      getList();
    }
  });
}
</script>

<style scoped lang="scss"></style>
